import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class RunBallAnimation extends JPanel implements ActionListener{
    private int width=640,height=480;//小球活动区域的大小
    private Ball ball; // 方块的初始 x 坐标

    public RunBallAnimation(Ball ball,int width,int height) {
        this.width = width;
        this.height = height;
        this.ball = ball;
        Timer timer = new Timer(10, this); // 创建一个定时器，每 10 毫秒触发一次 actionPerformed 方法
        timer.start(); // 启动定时器
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.black);
        g.drawRect(ball.getR(), ball.getR(), this.width, this.height);
        g.setColor(Color.blue);
        g.fillOval(ball.getX(),ball.getY(),2*ball.getR(),2*ball.getR());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        ball.move();
        repaint(); // 重新绘制面板
    }
}
